package gf.server.controller;

import gf.server.service.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.sql.Date;
import java.util.UUID;


/**
 * 文件Controller
 *
 * @author Gaofeng
 * @since 2021/10/17 13:44
 **/
@Controller
@RequestMapping("/file")

public class FileController {


    /*
     *构造函数注入FileService
     */
    private final FileService fileService;

    public FileController(FileService fileService) {
        this.fileService = fileService;
    }

    private final Logger logger = LoggerFactory.getLogger(getClass());

    /*
     * 文件路径
     */
    private final String dirPath = "D:\\Test\\";

    /*
     * 文件上传 post方式
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public String FileUploadServer(HttpServletRequest request, HttpServletResponse response) throws Exception {


        String uuid;
        uuid = UUID.randomUUID().toString();
        logger.info("接收文件的UUID=" + uuid);
        InputStream inStream = request.getInputStream();

        File file = new File(dirPath + "\\" + request.getHeader("time"));
        if (!file.exists()) {
            file.mkdir();
            logger.info("新建文件夹");
        }


        File newFile = new File(dirPath + request.getHeader("time") + "\\" + uuid + (request.getHeader("filetype")));
        FileOutputStream fos = new FileOutputStream(newFile);
        byte[] buffer = new byte[2048];
        int len;
        while ((len = inStream.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
        }

        /*
         * 文件大小
         */
        Long size = Long.valueOf(request.getHeader("fileSize"));

        /*
         * 文件类型
         */
        String type = request.getHeader("fileType");

        /*
         * 文件原始名字
         */
        String originalName = URLDecoder.decode(request.getHeader("fileName"), "UTF-8");


        /*
         * 文件创建时间
         */
        Date creatTime = new Date(System.currentTimeMillis());

        /*
         * 文件路径url
         */
        String url = dirPath + request.getHeader("time") + "\\" + uuid + (request.getHeader("filetype"));

        /*
         * 文件uuid
         */
        String uuidName = uuid;
        gf.server.entities.File file1 = new gf.server.entities.File(size, type, originalName, creatTime, url, uuidName);
        logger.info("上传文件详情" + newFile);

        fileService.addFile(file1);
        inStream.close();
        fos.close();
        logger.info("上传成功");
        return uuid;
    }

    /*
     * 文件下载   get方式
     */
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    @ResponseBody
    public void FileDownload(HttpServletRequest request, HttpServletResponse response) throws IOException {
        gf.server.entities.File uploadFile = fileService.findUrl(request.getHeader("uuid"));
        if (uploadFile == null) {
            response.setStatus(401);
            logger.info("文件不存在");
            return;
        }
        /*
         * 定位数据源
         */
        File f = new File(uploadFile.getUrl());
        /*
         * 建立管道
         */
        InputStream in = new FileInputStream(f);

        OutputStream out = new DataOutputStream(response.getOutputStream());
        response.setHeader("fileType", uploadFile.getType());
        response.setHeader("uuid", uploadFile.getUuidName());
        /*
         * 操作管道
         */
        byte[] buf = new byte[2048];
        int bytesRead;
        while ((bytesRead = in.read(buf)) > 0) {
            out.write(buf, 0, bytesRead);
        }
        in.close();
        out.close();
        logger.info("文件下载成功");

    }

}

